#-*-coding:utf-8-*-

from PyQt4 import QtCore, QtGui
import sys, os, zipfile, os.path, time, dircache, hashlib, shutil, bz2
import pisi.api, pisi
from pardus import Package
from tempfile import gettempdir
import comar

class Installer(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setWindowIcon(QtGui.QIcon(os.path.join("images","odun.png")))
        kritik = QtGui.QMessageBox.critical
        if len(sys.argv) < 2:
            kritik(self, "Hata!", u"PDZ dosyası belirtilmemiş!")
            sys.exit()
        else:
            if zipfile.is_zipfile(sys.argv[1]):
                self.setup = sys.argv[1]
            else:
                kritik(self, "Hata!", u"Bu Dosya PDZ dosyası değil!")
                sys.exit()
        self.resize(450, 210)
        self.gridLayout = QtGui.QGridLayout(self)
        self.logo = QtGui.QLabel(self)
        self.logo.setPixmap(QtGui.QPixmap(os.path.join("images","odun.png")))
        self.gridLayout.addWidget(self.logo, 0, 7, 7, 2)
        self.pisi_paketi = QtGui.QLabel(self)
        self.gridLayout.addWidget(self.pisi_paketi, 6, 0, 1, 7)
        self.progressBar = QtGui.QProgressBar(self)
        self.progressBar.setProperty("value", 0)
        self.gridLayout.addWidget(self.progressBar, 7, 0, 1, 9)
        self.buttonBox = QtGui.QPushButton(self)
        self.buttonBox.setEnabled(False)
        self.gridLayout.addWidget(self.buttonBox, 8, 8, 1, 1)
        self.bilgi_mesaji = QtGui.QLabel(self)
        self.gridLayout.addWidget(self.bilgi_mesaji, 5, 0, 1, 7)
        self.dosya_ismi = QtGui.QLabel(self)
        self.gridLayout.addWidget(self.dosya_ismi, 2, 0, 1, 8)
        self.retranslateUi()
        self.timer = QtCore.QBasicTimer()

        self.pzip = zipfile.ZipFile(u"%s"%self.setup)
        self.paket = []
        self.link = comar.Link()
        
        for pack in self.pzip.namelist():
            self.paket.append(pack)   
        
        self.onStart()
        
        QtCore.QObject.connect(self, QtCore.SIGNAL("say(int)"), self.progressBar.setValue)
        
    def onStart(self):
        self.timer.start(10, self)
    
    def retranslateUi(self):
        self.setWindowTitle(u"Odun Installer")
        self.pisi_paketi.setText(u"")
        self.progressBar.setFormat("%%p")
        self.bilgi_mesaji.setText(u"")
        self.dosya_ismi.setText(u"Setup: %s"%self.setup)
        self.buttonBox.setText(u"İptal")

    def timerEvent(self, event):
        self.progressBar.setMaximum(len(self.paket))
        extract_dir = os.path.join(gettempdir(),"odun-pisi")
        os.popen("rm -rf %s"%extract_dir)
        self.say = 0

        for pack in self.paket:
            self.say += 1
            self.pzip.extract(pack,extract_dir)
            self.bilgi_mesaji.setText(u"Paketler çıkarılıyor...")
            self.pisi_paketi.setText(pack) 
            print pack
            self.emit(QtCore.SIGNAL("say(int)"), self.say)
            app.processEvents()
            if not os.path.isdir(extract_dir):
                os.mkdir(extract_dir)
            self.pzip.extract(pack,extract_dir)
        
        list = dircache.listdir(extract_dir)
        
        l = []
        for i in list:
            if i[-19:] == "-pisi-index.xml.bz2":
                l.append(i)
            print i
        self.progressBar.setMaximum(len(l))
        self.say = 0
        for i in l: 
            print "-",i
            app.processEvents()
            self.bilgi_mesaji.setText(u"Indexler yükleniyor...")
            app.processEvents()
            self.pisi_paketi.setText(i)
            pindex_file = os.path.join(extract_dir, i)
            shutil.copyfile(pindex_file ,"/var/lib/pisi/index/%s/pisi-index.xml.bz2"%i[:-19])
            sha1sum = hashlib.sha1(open('/var/lib/pisi/index/%s/pisi-index.xml.bz2'%i[:-19],'rb').read()).hexdigest()
            f = open("/var/lib/pisi/index/%s/pisi-index.xml.bz2.sha1sum"%i[:-19], "w")
            f.write(sha1sum)
            f.close()
            pindex = bz2.decompress(open(pindex_file).read())
            f = open("/var/lib/pisi/index/%s/pisi-index.xml"%i[:-19], "w")
            f.write(pindex)
            f.close()
            self.say += 1
            self.emit(QtCore.SIGNAL("say(int)"), self.say)
            app.processEvents()
            time.sleep(1)
            
        self.pisi_paketi.setText("")
        time.sleep(1)
        self.bilgi_mesaji.setText(u"Veritabanı inşa ediliyor...")
        app.processEvents()
        self.link.System.Manager["pisi"].updateAllRepositories()
        #pisi.api.rebuild_db()
        self.bilgi_mesaji.setText(u"Veritabanı inşası bitti.")
        pisi_dir = os.path.join(extract_dir, "packages")
        pisi_list = dircache.listdir(pisi_dir)
        pkgs = []
        app.processEvents()
        self.bilgi_mesaji.setText(u"Paketler kuruluyor...")
        self.progressBar.setMaximum(len(pisi_list))
        self.say = 0
        for package in pisi_list:
            full_path = os.path.join(pisi_dir, package)
            self.pisi_paketi.setText(package)
            app.processEvents()
            self.link.System.Manager["pisi"].installPackage(full_path)
            self.say += 1
            self.emit(QtCore.SIGNAL("say(int)"), self.say)

        self.close()
        self.timer.stop()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ui = Installer()
    ui.show()
    sys.exit(app.exec_())
